<?php
namespace Common\Controller;
//图片上传类
class PicUploadController extends \Think\Controller{
    
    public function index(){
        if(IS_POST){
            $upload           = new \Think\Upload();
            $upload->maxSize  = 10145728 ;  
            $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
            $path = '/Upload/';
            $upload->rootPath = $_SERVER['DOCUMENT_ROOT'].$path;
            $upload->savePath = 'admin/';
            $file = array_values($_FILES);
            $info             = $upload->uploadOne($file[0]);
            if(!$info){
                echo json_encode(array('status'=>0,'info'=>$upload->getError()));die;
            }else{
                $this->thumb($upload->rootPath.$info['savepath'].$info['savename']);//缩略裁剪
                echo json_encode(array('status'=>1,'info'=>$path.$info['savepath'].$info['savename']));die;
            }
		}
    }
	
    //生成做略图
	public function thumb($img, $width = 900, $height = 900){
		$image = new \Think\Image();
        $image->open($img);
        $size = $image->size();
        if($size[0] <= $width && $size[1] <= $height) return;
        $image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save($img);
    }
    
    //摇一摇周边--上传缩略图
    public function shake_upload(){
    	if(IS_POST){
    		$upload           = new \Think\Upload();
    		$upload->maxSize  = 10145728 ;
    		$upload->exts     = array('jpg', 'gif', 'png', 'jpeg');
    		$path = '/Upload/';
            $upload->rootPath = $_SERVER['DOCUMENT_ROOT'].$path;
            $upload->savePath = 'admin/';
    		$file = array_values($_FILES);
    		$info             = $upload->uploadOne($file[0]);
    		if(!$info){
    			echo json_encode(array('status'=>0,'info'=>$upload->getError()));die;
    		}else{
    			$this->thumb($upload->rootPath.$info['savepath'].$info['savename'], 120, 120);//缩略裁剪

    			//上传图片素材
    			$imgPath = $upload->rootPath.$info['savepath'].$info['savename'];
    			$result   = D('Shake')->uploadPic($imgPath);
    			if($result['errcode'] === 0){
    				exit(json_encode(array('status'=>1,'info'=>$result['data']['pic_url'])));
    			}else{
    				exit(json_encode(array('status'=>0,'info'=>$result)));
    			}
    
    		}
    	}
    }
    
    //上传微信js所需的认证文件
    public function wx_grant() {
    	$files = $_FILES;
    	$file = array_values($files);
    	$file = $file[0];
    
    	if ($file['error'] > 0) {
    		$res = array('status'=>0,'info'=>'错误：'.$file['error']);
    	} elseif ($file['type'] != 'text/plain') {
    		$res = array('status'=>0,'info'=>'文件后缀不允许');
    	}  elseif ($file['size'] > 1145728) {
    		$res = array('status'=>0,'info'=>'文件大小超过限制');
    	} else {
    		move_uploaded_file($file['tmp_name'], '../'.$file['name']);
    		$res = array('status'=>1,'info'=>'上传成功');
    	}
    	echo json_encode($res);
    }
}